package com.common.dongqiuhui.apps.comm.net;

import android.content.Context;
import android.text.TextUtils;

import com.common.dongqiuhui.apps.comm.exception.ServerException;
import com.common.dongqiuhui.apps.comm.tools.BallLog;
import com.common.dongqiuhui.apps.comm.tools.BallUtil;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.SyncHttpClient;
import com.loopj.android.http.TextHttpResponseHandler;

import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

public class BallPhotoHttp {

	private static final String TAG = BallPhotoHttp.class.getSimpleName();
	private static SyncHttpClient mSyncHttpClient = new SyncHttpClient();
	private static Context appContext = null;

    public static void setContext(Context context) {
        if (appContext == null) {
            appContext = context.getApplicationContext();
        }
    }
	private static boolean isNameValuePairExist(String name,
			List<NameValuePair> params) {
		if (params == null) {
			return false;
		}

		for (NameValuePair nv : params) {
			if (nv.getName().equals(name)) {
				return true;
			}
		}

		return false;
	}


	private static void setAuthInfo(AsyncHttpClient client, String host) {
		if (client != null) {
//			if (isDev) {
//				// client.setBasicAuth(USER_NAME, PASSWORD,
//				// new AuthScope(host, 80));
//				Credentials credentials = new UsernamePasswordCredentials(
//						USER_NAME, PASSWORD);
//				((DefaultHttpClient) client.getHttpClient())
//						.getCredentialsProvider().setCredentials(
//								new AuthScope(host, 80), credentials);
//
//			} else {
//				client.clearBasicAuth();
			//}
		}
	}

	private static String getHost(String url) {
		String ret = url.substring(7, url.indexOf('/', 7));
		return ret;
	}

	private static RequestParams convertParams(List<NameValuePair> params) {
		RequestParams result = new RequestParams();
        if(params!=null&&params.size()>0) {
            for (NameValuePair bean : params) {
                if (!TextUtils.isEmpty(bean.getName())) {
                    result.put(bean.getName(), bean.getValue());
                }
            }
        }
		return result;
	}

	private static class SyncHttpResponseHandler extends
			TextHttpResponseHandler {
		private String mResult = null;
		private int mStatusCode = 0;
		private CustomMultipartEntity mProgressListener = null;
		private Context mContext;

        public Header[] getmHeaders() {
            return mHeaders;
        }

        private Header[] mHeaders;



		public SyncHttpResponseHandler() {
		}

		public SyncHttpResponseHandler(Context context) {
			mContext = context;
		}

		public void setProgressListener(CustomMultipartEntity l) {
			mProgressListener = l;
		}


		public String getResult() {
			return mResult;
		}

		public int getStatusCode() {
			return mStatusCode;
		}

		@Override
		public void onFailure(int statusCode, cz.msebera.android.httpclient.Header[] headers, String responseString, Throwable arg3) {
			mStatusCode = statusCode;
			mResult = responseString;
            mHeaders=headers;
		}

		@Override
		public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header[] headers, String responseString) {
			mStatusCode = statusCode;
			mResult = responseString;
            mHeaders=headers;
		}
		@Override
		public void onProgress(long bytesWritten, long totalSize) {
			super.onProgress(bytesWritten, totalSize);
			if (mContext != null && !BallUtil.hasNetwork(mContext)) {
			}else{
				if (null != mProgressListener) {
					mProgressListener.transferred(bytesWritten, totalSize);
				}
			}
		}

	}
    private static boolean useQiniu=true;
    public static String postPhoto(final Context context,final String url, final ArrayList<NameValuePair> params,
    		final ArrayList<File> files) throws ParseException, IOException {
    	return postPhoto(context, url, params, files, null);
    	
    }
	public static String postPhoto(Context context, String url,
			ArrayList<NameValuePair> params, final ArrayList<File> files,
			CustomMultipartEntity progressListener) throws ParseException,
			IOException {
		RequestParams newParams = null;
		if (!TextUtils.isEmpty(url)) {
			newParams = convertParams(params);
			if(files!=null&&files.size()>0){
				if(!useQiniu){
					for (int i=0;i<files.size();i++){
						File file=files.get(i);
						if (null != file) {
							newParams.put("pic_data["+i+"]", file);
						}
					}
				}
			}
			
		}
		BallLog.i(TAG,
				AsyncHttpClient.getUrlWithQueryString(false, url, newParams));
		SyncHttpResponseHandler res = new SyncHttpResponseHandler(context);
		res.setProgressListener(progressListener);
		if (BallUtil.hasNetwork(appContext)) {
            mSyncHttpClient.post(url, newParams, res);
        } else if (res != null) {
			res.sendFailureMessage(0, null, null, new Throwable(
					"recvfrom failed: ECONNRESET (Connection reset by peer)"));
		}
		if (HttpStatus.SC_OK == res.getStatusCode()) {
            return res.getResult();
		} else {
			throw new ServerException("The network info is :"
					+ BallUtil.getNetType(appContext)
					+ ";The request url is :"
					+ url
					+ AsyncHttpClient.getUrlWithQueryString(false, url,
					newParams) + "The response status code is :"
					+ res.getStatusCode());
		}
	}
}
